package qsoft.omanga.common.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import qsoft.omanga.ui.R;

public class QueueLoad {
	private static final QueueLoad QUEUE_LOAD = new QueueLoad();

	public static final QueueLoad getInstance() {
		return QUEUE_LOAD;
	}

	private final int poolThreads = 5;
	private final Map<ImageView, String> ivTasks = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	private final ExecutorService pool = Executors
			.newFixedThreadPool(poolThreads);

	public void queueJob(final ImageView imageView, final String id,
			final String url, final String sizeImage) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				String tag = ivTasks.get(imageView);
				if (tag != null && tag.equals(url)) {
					if (msg.obj != null) {
						Cache.getInstance().putSoftCacheImage(url,
								(Bitmap) msg.obj);
						imageView.setImageBitmap((Bitmap) msg.obj);
						Log.i("Result " + id, "Success..");
					} else {
						imageView.setImageResource(R.drawable.ic_launcher);
						Log.e("Result " + id, "Failure..");
					}
				}
			}

		};

		pool.submit(new Runnable() {
			@Override
			public void run() {
				final Bitmap bmp = loadBitmap(url);
				Message message = Message.obtain();
				message.obj = bmp;
				handler.sendMessage(message);
				Log.d("Item downloaded from Server: " + id, "Process...");
			}
		});
	}

	private Bitmap loadBitmap(String txtURL) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(txtURL);
			URLConnection conn = url.openConnection();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException", e.getMessage());
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
		}
		return bitmap;
	}

	public void forceLoad(ImageView imageView, String id, String url,
			String sizeImage) {
		ivTasks.put(imageView, id);
		Bitmap bitmap = Cache.getInstance().getSoftCacheImage(id);

		// check in UI thread, so no concurrency issues
		if (bitmap != null) {
			Log.i("Item loaded from cache: " + id, "Success..");
			imageView.setImageBitmap(bitmap);
		} else {
			imageView.setImageResource(R.drawable.ic_launcher);
			queueJob(imageView, id, url, sizeImage);
		}
	}
}
